const db = require("../db");
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config')

exports.regRouter = (req, res) => {
    const userinfo = req.body;
    if (!userinfo.username || !userinfo.password) {
        return res.send({ status: 1, message: '用户名或密码不能为空！' })
    }
    const query1 = `select * from users where username=?`
    db.query(query1, [userinfo.username], (err, data) => {
        var obj = {
            data: {},
            meta: {
                status: '',
                msg: ''
            }
        }
        if (err) {
            obj.meta.status = 500;
            obj.meta.msg = '数据库查询错误';
            return res.send(obj);
        }
        if (data.length > 0) {
            obj.meta.status = 500;
            obj.meta.msg = '用户名已被占用';
            return res.send(obj);
        }
        userinfo.password = bcrypt.hashSync(userinfo.password, 10)
        var params = {
            username: userinfo.username,
            password: userinfo.password,
            nickname: userinfo.nickname
        }

        const query2 = `insert into users set ?`
        db.query(query2, params, (err, data) => {
            if (err) {
                obj.meta.status = 500;
                obj.meta.msg = err;
                return res.send(obj);
            }
            if (data.affectedRows !== 1) {
                obj.meta.status = 500;
                obj.meta.msg = '注册失败';
                return res.send(obj);
            }
            obj.meta.status = 200;
            obj.meta.msg = '注册成功！';
            return res.send(obj);
        })
    })
}

exports.loginRouter = (req, res) => {
    var obj = {
        data: {},
        meta: {
            status: '',
            msg: ''
        }
    }
    const userinfo = req.body;
    if (!userinfo.username || !userinfo.password) {
        obj.meta.status = 400;
        obj.meta.msg = '用户名或密码不能为空';
        return res.send(obj);
    }
    const query1 = `select * from users where username=?`
    db.query(query1, [userinfo.username], (err, data) => {
        if (err) {
            obj.meta.status = 500;
            obj.meta.msg = '数据库查询错误';
            return res.send(obj);
        }
        if (data.length !== 1) {
            obj.meta.status = 500;
            obj.meta.msg = '用户名不存在';
            return res.send(obj);
        }
        const flag = bcrypt.compareSync(userinfo.password, data[0].password)
        if (!flag) {
            obj.meta.status = 500;
            obj.meta.msg = '用户名或密码错误';
            return res.send(obj);
        }
        const user = { ...data[0], password: '', user_pic: '' }
        const tokenStr = jwt.sign(user, config.jwtSecretKey, {
            expiresIn: '2400h'
        })
        obj.meta.status = 200;
        obj.meta.msg = "登录成功";
        obj.data.token = "Bearer " + tokenStr;
        obj.data.id = data[0]['id'];
        obj.data.username = data[0]['username'];
        return res.send(obj);
    })
}
